package com.brsya.base.net;


import com.brsya.base.base.BaseView;
import com.brsya.base.base.Contents;
import com.brsya.base.bean.BaseBean;
import com.brsya.base.util.LoggerUtil;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 网络请求回调
 * @param <T> 回调数据泛型
 */
public abstract class MyObserver<T extends BaseBean> implements Observer<T> {
    private BaseView mView;

    public MyObserver(BaseView mView) {
        this.mView = mView;
    }

    @Override
    public void onNext(@NonNull T baseBean) {
        complete(baseBean);
        if (baseBean.getCode() == Contents.NET_SUCCESS_CODE) {
            success(baseBean);
        } else {
            LoggerUtil.e("接口访问错误");
            onFail(baseBean.getCode(), baseBean.getMsg());
        }

    }

    @Override
    public void onError(@NonNull Throwable e) {
        error(e);
    }

    @Override
    public void onComplete() {

    }

    public void onFail(int status, String msg) {
        if (mView != null) {
            mView.onFail(status, msg);
        }
    }

    public void complete(@NonNull T baseBean) {
        if (mView != null) {
            mView.hideLoading();
        }
    }

    public void error(@NonNull Throwable e) {
        if (mView != null) {
            LoggerUtil.e("------------------网络错误：");
            e.printStackTrace();
            LoggerUtil.e("------------------网络错误");
            mView.onError(e.getMessage());
        }
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    public abstract void success(@NonNull T baseBean);

}
